const {mysql} = require('../qcloud')

module.exports = async (ctx) => {
    // 轮播图
    const banner = await mysql('nideshop_ad')
        .where({ad_position_id: 1})
        .select()
    // 类型
    const channel = await mysql('nideshop_channel').select()

    // 品牌制造商直供
    const brandList = await mysql('nideshop_brand')
        .where({is_new: 1})
        .orderBy('new_sort_order', 'asc')
        .limit(4)
        .select()

    // 新品首发
    const newGoos = await mysql('nideshop_goods')
        .column('id', 'name', 'list_pic_url', 'retail_price', 'goods_brief')
        .orderBy('id', 'desc')
        .limit(6)
        .select()

    // 人气推荐
    const hotGoods = await mysql('nideshop_goods')
        .column('id', 'name', 'list_pic_url', 'retail_price', 'goods_brief')
        .where({is_hot: 1})
        .limit(6)
        .select()

    // 专题精选
    const topicList = await mysql('nideshop_topic')
        .limit(3)
        .select()

    // 选出分类
    const categoryList = await mysql('nideshop_category')
        .where({parent_id: 0})
        .select()

    const newCategoryList = []

    for (let i = 0; i < categoryList.length; i++) {
        var item = categoryList[i]
        // 用每个分类的id 找出所有相同的id（归一类）
        let childCategoryIds = await mysql('nideshop_category')
            .where({parent_id: item.id})
            .column('id')
            .select()

        // 把每一类的 对象  转为  数组
        childCategoryIds = childCategoryIds.map((item) => {
            return item.id
        })

        // 把每一类的里面的id  找到对应的商品  （whereIn）
        const categoryGoods = await mysql('nideshop_goods')
            .column('id', 'name', 'list_pic_url', 'retail_price', 'is_hot', 'sell_volume')
            .whereIn('category_id', childCategoryIds)
            .limit(7)
            .select()
        // 把每一类商品push到新数组
        newCategoryList.push({
            'id': item.id,
            'name': item.name,
            'goodsList': categoryGoods
        })
    }

    ctx.state.data = {
        banner,
        channel,
        brandList,
        newGoos,
        hotGoods,
        topicList,
        newCategoryList
    }
}
